package com.aididi.controller;

import com.aididi.utils.MinioUtils;
import com.aididi.utils.R;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.ZonedDateTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ：xuzexiang
 * @description：上传文件
 * @date ： 2021/11/4 9:47
 */
@RestController
@CrossOrigin
public class UploadController {


    @Autowired
    private MinioUtils minioComp;


    /**
     * 传统方式上传
     * @param file
     * @param fileName
     * @return
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file, @RequestParam("fileName") String fileName) {
        minioComp.upload(file,fileName);
        String url = minioComp.getUrl(fileName, 7, TimeUnit.DAYS);
        return R.success(url);
    }


    /**
     * 前端formData方式直传
     * @param fileName
     * @return
     */
    @GetMapping("/policy")
    public R policy(@RequestParam("fileName")String fileName) {
        Map policy = minioComp.getPolicy(fileName, ZonedDateTime.now().plusMinutes(10));
        return R.success(policy);
    }

    /**
     * 签名url方式上传
     * @param fileName
     * @return
     */
    @GetMapping("/uploadUrl")
    public R uploadUrl(@RequestParam("fileName") String fileName) {
        String url = minioComp.getPolicyUrl(fileName, Method.PUT, 2, TimeUnit.MINUTES);
        return R.success(url);
    }

    /**
     * 获取签名后的文件url
     * @param fileName
     * @return
     */
    @GetMapping("/url")
    public R getUrl(@RequestParam("fileName")String fileName) {
        String url = minioComp.getUrl(fileName, 7, TimeUnit.DAYS);
        return R.success(url);
    }


}
